<!--线上产品进件-->
<template>
  <div class="app-container">
    <el-card>
      <el-form
        :model="queryParams"
        :rules="rulesForm"
        ref="queryForm"
        :inline="true"
        label-width="150px"
      >
        <el-form-item label="选择产品" prop="relation">
          <div style="">
            <div class="product-img">
              <div
                class="product-img-box"
                v-for="(item, idx) in queryParams.relation"
                :key="item.id"
              >
                <el-tooltip effect="dark" :content="item.name" placement="top">
                  <img style="" :src="item.pic" alt="" />
                </el-tooltip>

                <i
                  @click="delProduct(idx, item.id)"
                  style="color: #ccc; font-weight: bold"
                  class="el-icon-close i2"
                ></i>
              </div>

              <div
                style="line-height: 96px; margin-right: 10px"
                v-if="queryParams.relation.length < 1"
              >
                <div class="uploadPic" @click="selectPic()">
                  <i
                    style="
                            font-size: 40px;
                            color: #ccc;
                            font-weight: bold;
                          "
                    class="el-icon-plus i1"
                  ></i>
                </div>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="计件类型" prop="pieceType">
          <el-select
            v-model="queryParams.pieceType"
            clearable
            placeholder="请选择计件类型"
            @change="pieceChange"
          >
            <el-option
              v-for="item in rateTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <!--<span>计件比例、计件定额</span>-->
        </el-form-item>
        <el-form-item
          v-if="queryParams.pieceType == 'ratio'"
          label="结算方式"
          prop="stlmtMethod"
        >
          <el-radio
            @change="radioChange"
            v-model="queryParams.stlmtMethod"
            :label="item.value"
            v-for="(item, index) in radioMethodList"
            :key="index"
            >{{ item.label }}</el-radio
          >
          <!--<el-radio v-model="queryParams.stlmtMethod" label="2">复合结算</el-radio>-->
        </el-form-item>
        <el-form-item
          v-if="queryParams.stlmtMethod == '1'"
          :key="key0"
          label="结算节点"
          prop="stlmtNode"
        >
          <el-select
            v-model="queryParams.stlmtNode"
            clearable
            placeholder="请选择结算节点"
          >
            <el-option
              v-for="item in settleNodeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <!--<span>提款结算、放款结算、授信结算</span>-->
        </el-form-item>
        <el-form-item
          v-if="queryParams.stlmtMethod == '2'"
          :key="key1"
          label="结算节点"
          prop="stlmtNode1"
        >
          <el-select
            multiple
            v-model="queryParams.stlmtNode1"
            clearable
            @change="multChange"
            placeholder="请选择结算节点"
          >
            <el-option
              v-for="item in settleNodeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <!--<span>提款结算、放款结算、授信结算</span>-->
        </el-form-item>

        <div v-if="queryParams.stlmtMethod == 2">
          <el-form-item
            v-if="queryParams.stlmtNode1&&queryParams.stlmtNode1.includes('withdrawal')"
            label="提款结算（税后）"
            prop="withdrawalRatio"
          >
            <el-input
              v-model="queryParams.withdrawalRatio"
              max="100"
              min="0"
              type="number"
              @input="amountInput($event,'withdrawalRatio')"
              placeholder="请输入结算佣金比例"
            >
              <template slot="suffix">%</template>
            </el-input>
          </el-form-item>
          <el-form-item
            v-if="queryParams.stlmtNode1&&queryParams.stlmtNode1.includes('lenders')"
            label="放款结算（税后）"
            prop="lendersRatio"
          >
            <el-input
              v-model="queryParams.lendersRatio"
              max="100"
              min="0"
              type="number"
              @input="amountInput($event,'lendersRatio')"
              placeholder="请输入结算佣金比例"
            >
              <template slot="suffix">%</template>
            </el-input>
          </el-form-item>
          <el-form-item
            v-if="queryParams.stlmtNode1&&queryParams.stlmtNode1.includes('credit')"
            label="授信结算（税后）"
            prop="creditRatio"
          >
            <el-input
              v-model="queryParams.creditRatio"
              max="100"
              min="0"
              type="number"
              @input="amountInput($event,'creditRatio')"
              placeholder="请输入结算佣金比例"
            >
              <template slot="suffix">%</template>
            </el-input>
          </el-form-item>
        </div>

        <el-form-item label="结算佣金（税后）"  v-if="queryParams.stlmtMethod == 1" prop="stlmtAmount">
          <el-input
            v-model="queryParams.stlmtAmount"
            type="number"
            @input="amountInput($event,'stlmtAmount')"
            placeholder="请输入结算佣金"
          >
            <template slot="suffix" v-if="queryParams.pieceType == 'ratio'"
              >%</template
            >
            <template slot="suffix" v-else>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="审批时效" prop="vertifyAging">
          <el-input
            v-model="queryParams.vertifyAging"
            maxlength="200"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="有效时间" prop="effectiveTime">
          <el-date-picker
            v-model="queryParams.effectiveTime"
            type="daterange"
            value-format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结算规则" prop="stlmtRule">
          <el-input
            type="textarea"
            v-model="queryParams.stlmtRule"
            maxlength="500"
            placeholder="请输入结算规则"
          ></el-input>
        </el-form-item>
        <el-form-item label="数据方式" prop="dataMode">
          <el-input
            type="textarea"
            v-model="queryParams.dataMode"
            maxlength="500"
            placeholder="请输入数据方式"
          ></el-input>
        </el-form-item>
      </el-form>
    </el-card>
    <div class="bottomClass">
      <el-button style="width: 100px" @click="cancelClick">取消</el-button>
      <el-button type="primary" style="width: 100px" @click="saveForm"
        >保存</el-button
      >
    </div>
  </div>
</template>

<script>
import {
  settleMentAddApi,
  settleMentDetailApi,
  settleMentUpdateApi
} from "../../../api/commission";

export default {
  data() {
    const validatestlmtAmount = (rule, value, callback) => {
      let reg = /^(?:0|[1-9][0-9]?)$|(?:[0-9]?\d(?:\.\d+))$/;
      // /^(?:100(?:\.0*)?)|(?:[0-9]?\d(?:\.\d+)?)$/
      if (this.queryParams.pieceType == "ratio") {
        if (this.queryParams.stlmtMethod == "1" || this.queryParams.stlmtMethod == "2") {
          if (value == "") {
            callback(new Error("请输入结算佣金比例"));
          } else {
            if (!reg.test(value)) {
              callback(new Error("请输入0-100之内的数字"));
            } else {
              callback();
            }
          }
        }
      } else if (this.queryParams.pieceType == "quota") {
        if (value == "") {
          callback(new Error("请输入结算佣金"));
        } else {
          if (value < 0) {
            callback(new Error("请输入正数"));
          } else {
            callback();
          }
        }
      } else  {
        if (value == "" && this.queryParams.pieceType == "quota") {
          callback(new Error("请输入结算佣金"));
        } else if (value == "" && this.queryParams.pieceType == "ratio") {
          callback(new Error("请输入结算佣金比例"));
        } else {
          callback();
        }
      }
    };
    const validateWithdrawalRatio = (rule, value, callback) => {
      let reg = /^(?:0|[1-9][0-9]?)$|(?:[0-9]?\d(?:\.\d+))$/;
      if (value == "") {
        callback(new Error("请输入提款结算"));
      } else {
        if (!reg.test(value)) {
          callback(new Error("请输入0-100之内的数字"));
        } else {
          callback();
        }
      }
    };
    const validatelendersRatio = (rule, value, callback) => {
      let reg = /^(?:0|[1-9][0-9]?)$|(?:[0-9]?\d(?:\.\d+))$/;
      if (value == "") {
        callback(new Error("请输入放款结算"));
      } else {
        if (!reg.test(value)) {
          callback(new Error("请输入0-100之内的数字"));
        } else {
          callback();
        }
      }
    };
    const validatecreditRatio = (rule, value, callback) => {
      let reg = /^(?:0|[1-9][0-9]?)$|(?:[0-9]?\d(?:\.\d+))$/;
      if (value == "") {
        callback(new Error("请输入授信结算"));
      } else {
        if (!reg.test(value)) {
          callback(new Error("请输入0-100之内的数字"));
        } else {
          callback();
        }
      }
    };
    return {
      key0: 0,
      key1: 1,
      queryParams: {
        relation: [],
        pieceType: "", //计件类型
        stlmtMethod: "1", // 结算方式
        stlmtNode: "",
        stlmtNode1: [],
        stlmtAmount: "",
        vertifyAging: "",
        effectiveTime: "",

        stlmtRule: "", //结算规则
        dataMode: "", //数据方式
        // 复合结算
        withdrawalRatio: "", // 提款结算
        lendersRatio: "", // 放款结算
        creditRatio: "" //授信结算
      },
      rateTypeList: [], // 计件类型
      settleNodeList: [], //结算节点
      radioMethodList: [], // 结算方式
      rulesForm: {
        relation: [
          { required: true, message: "请选择产品", trigger: ["change", "blur"] }
        ],
        pieceType: [
          {
            required: true,
            message: "请选择计件类型",
            trigger: ["change", "blur"]
          }
        ],
        stlmtMethod: [
          {
            required: true,
            message: "请选择结算方式",
            trigger: ["change", "blur"]
          }
        ],
        stlmtNode: [
          {
            required: true,
            message: "请选择结算节点",
            trigger: ["change", "blur"]
          }
        ],
        stlmtAmount: [
          {
            required: true,
            trigger: ["change", "blur"],
            validator: validatestlmtAmount
          }
        ],
        effectiveTime: [
          {
            required: true,
            message: "请选择有效时间",
            trigger: ["change", "blur"]
          }
        ],
        withdrawalRatio: [
          {
            required: true,
            trigger: ["change", "blur"],
            validator: validateWithdrawalRatio
          }
        ],
        lendersRatio: [
          {
            required: true,
            trigger: ["change", "blur"],
            validator: validatelendersRatio
          }
        ],
        creditRatio: [
          {
            required: true,
            trigger: ["change", "blur"],
            validator: validatecreditRatio
          }
        ]
      }
    };
  },
  async created() {
    this.rateTypeList = await this.$getDictData("piece_type");
    this.radioMethodList = await this.$getDictData("settlement_method");
    this.settleNodeList = await this.$getDictData("stlmt_node");
    if (this.$route.query.key == "update") {
      this.$route.meta.title = "编辑结算规则";
      this.getDetail(this.$route.query.id);
    } else {
      this.$route.meta.title = "新增结算规则";
    }
  },
  methods: {
    amountInput(val,str) {
      let arr = val.split('.')
      if (arr.length > 1) {
        this.queryParams[str] = arr[0] + '.' +arr[1].slice(0,2)
      }
    },
    delProduct(idx, id) {
      console.log(idx, id, this.queryParams.relation, this.queryParams);
      // return;
      this.queryParams.productIdList.splice(idx, 1);
      const i = this.queryParams.relation.findIndex(v => {
        return v.id === id;
      });

      if (i != -1) {
        this.queryParams.relation.splice(i, 1);
      }
    },
    selectPic() {
      let that = this;
      that.$modalGoodList(
        function(row) {
          if (row) {
            let app = row.map(v => {
              return {
                id: v.id,
                name: v.name,
                pic: v.pic
              };
            });
            that.$set(that.queryParams, "relation", app);
            that.$refs.queryForm.validateField("relation");
            this.$set(
              that.queryParams,
              "productIdList",
              row.map(v => {
                return v.id;
              })
            );
          }
        },
        "1",
        that.queryParams.productIdList
      );
    },
    pieceChange(val) {
      if (val == "quota") {
        this.queryParams.stlmtMethod = "1";
        this.queryParams.stlmtNode = "";
      } else if (val == "ratio") {
        this.$set(this.queryParams,'stlmtNode1',[])
      }
    },
    radioChange(val) {
      this.key0++;
      this.key1++;
      this.$set(this.queryParams, "stlmtNode", "");
      this.$set(this.queryParams, "stlmtNode1", []);
    },
    multChange(val) {
      if (!val.includes("withdrawal")) {
        this.queryParams.withdrawalRatio = "";
      }
      if (!val.includes("lenders")) {
        this.queryParams.lendersRatio = "";
      }
      if (!val.includes("credit")) {
        this.queryParams.creditRatio = "";
      }
    },
    saveForm() {
      this.$refs.queryForm.validate(validate => {
        if (validate) {
          if (this.$route.query.key == "add") {
            this.addSettle();
          }
          if (this.$route.query.key == "update") {
            this.updateSettle();
          }
        }
      });
    },
    addSettle() {
      let params = this.handleDate();
      settleMentAddApi(params).then(res => {
        this.$router.push({ path: "/commission/settlementRules/index" });
        return this.$message.success("新增成功！");
      });
    },
    handleDate() {
      this.queryParams.startTime = this.queryParams.effectiveTime[0];
      this.queryParams.stopTime = this.queryParams.effectiveTime[1];
      // this.queryParams.pieceType = this.queryParams.pieceType == '1' ? 'ratio' : 'quota'
      this.queryParams.productId = this.queryParams.relation[0].id;
      this.queryParams.productName = this.queryParams.relation[0].name;
      this.queryParams.productPic = this.queryParams.relation[0].pic;
      if (this.queryParams.stlmtMethod == "2") {
        this.queryParams.stlmtNode = this.queryParams.stlmtNode1.join(",");
      }
      if (this.queryParams.pieceType == "ratio" && this.queryParams.stlmtMethod == "1") {
        this.$set(this.queryParams, "stlmtRatio", this.queryParams.stlmtAmount);
        // this.queryParams.stlmtAmount = "";
      }
      if (this.queryParams.pieceType == "ratio" && this.queryParams.stlmtMethod == "2") {
        this.$set(this.queryParams, "stlmtRatio", this.queryParams.stlmtAmount);
        // this.queryParams.stlmtAmount = "";
      }
      let params = JSON.parse(JSON.stringify(this.queryParams));
      delete params.effectiveTime;
      delete params.productIdList;
      delete params.relation;
      delete params.stlmtNode1;
      return params;
    },
    updateSettle() {
      let params = this.handleDate();
      settleMentUpdateApi(params).then(res => {
        this.$router.push({ path: "/commission/settlementRules/index" });
        return this.$message.success("修改成功！");
      });
    },
    getDetail(id) {
      settleMentDetailApi(id).then(res => {
        if (res.code == 200) {
          let data = JSON.parse(JSON.stringify(res.data));
          this.$set(data, "relation", [
            {
              id: data.productId,
              name: data.productName,
              pic: data.productPic
            }
          ]);
          if (data.pieceType == "ratio" && data.stlmtMethod == 2) {
            this.$set(data, "stlmtNode1", data.stlmtNode.split(","));
          }
          data.stlmtMethod = data.stlmtMethod.toString();
          this.$set(data, "effectiveTime", []);
          this.$set(data, "productIdList", [data.productId])
          if (data.pieceType == "ratio" && data.stlmtMethod == 1) { //计件比例 单节点结算
            data.stlmtAmount = res.data.stlmtRatio
          }
          if (data.pieceType == "ratio" && data.stlmtMethod == "2") {
            data.stlmtAmount = res.data.stlmtRatio;
          }
          data.effectiveTime[0] = data.startTime;
          data.effectiveTime[1] = data.stopTime;
          this.queryParams = data;
        }
      });
    },
    cancelClick() {
      this.$router.go(-1);
    }
  }
};
</script>

<style lang="scss" scoped>
/deep/ .el-form-item {
  display: block;
}
.bottomClass {
  width: 100%;
  background: #ffffff;
  text-align: center;
  margin-top: 20px;
}
/deep/ .el-select,
/deep/ .el-date-editor {
  width: 600px;
  //height: 48px;
}
/deep/ .el-range-separator {
  //line-height: 30px;
}
/deep/ .el-input {
  input {
    width: 600px;
    //height: 48px;
  }
}
/deep/ .el-textarea {
  width: 1000px;
  height: 160px;
}
/deep/ .el-textarea__inner {
  height: 160px;
}
.product-img {
  width: 1000px;
  display: flex;
  flex-wrap: wrap;
  .product-img-box {
    position: relative;
    .i2 {
      position: absolute;
      right: -1px;
      top: -5px;
    }
  }
  .uploadPic {
    width: 96px;
    height: 96px;
    // margin-left: 10px;
    background: #eeeeee;
    border-radius: 8px;
    position: relative;

    .i1 {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
  }

  img {
    width: 96px;
    height: 96px;
    margin-right: 13px;
  }
}
</style>
